package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go-web-app-demo/common"
	"go-web-app-demo/model"
	internalValidator "go-web-app-demo/pkg/validator"
	"go-web-app-demo/router"
	"go-web-app-demo/service"
	"go.uber.org/zap"
	"net/http"
)

func init() {

	router.AddHandler(&router.Handler{
		Method:       "post",
		RelativePath: "/signup",
		HandleFunc:   SignUp,
		NeedAuth:     false,
	})

	router.AddHandler(&router.Handler{
		Method:       "post",
		RelativePath: "/login",
		HandleFunc:   Login,
		NeedAuth:     false,
	})
	zap.L().Info("controller.user.go init")
}

func SignUp(c *gin.Context) {

	var s model.SignUpRequest
	if err := c.ShouldBindJSON(&s); err != nil {
		zap.L().Error("SignUp with invalid param", zap.Error(err))

		if errs, ok := err.(validator.ValidationErrors); ok {

			c.JSON(http.StatusBadRequest, common.NewFailed(internalValidator.RemoveTopStruct(errs.Translate(internalValidator.Trans))))
			return
		}

		c.JSON(http.StatusBadRequest, common.NewFailed(err.Error()))
		return
	}

	r := service.SignUp(&s)
	c.JSON(http.StatusOK, r)
}

func Login(c *gin.Context) {
	var s *model.LoginRequest
	if err := c.ShouldBindJSON(&s); err != nil {
		zap.L().Error("Login with invalid param", zap.Error(err))

		if errs, ok := err.(validator.ValidationErrors); ok {

			c.JSON(http.StatusBadRequest, common.NewFailed(internalValidator.RemoveTopStruct(errs.Translate(internalValidator.Trans))))
			return
		}

		c.JSON(http.StatusBadRequest, common.NewFailed(err.Error()))
		return
	}

	r := service.Login(s)

	if r.IsSucceed() {
		c.Header("Token", r.Payload.(string))
	}

	c.JSON(http.StatusOK, r)
}
